using System;
using System.Runtime.Serialization.Formatters.Binary ;
using System.IO;
using System.Diagnostics;
using AppliedRecognition.Util;
using System.Collections.Generic;
namespace AppliedRecognition.Speech.TaskSupport {

	/// <summary>
	/// Obtains list of tasks which are visible in task list
	/// </summary>
	[Serializable]
	public class TaskVisibleTasks: EnumWindows {
        private List<IntPtr> _excWindows = new List<IntPtr>(); 
		
		private ARTraceSwitch CommandTS= new ARTraceSwitch("Command", "Actions");


		public TaskVisibleTasks() 
		{
		}
		public TaskVisibleTasks(IntPtr hwndOwnerWindow) 
		{
			ExcludedWindows.Add(hwndOwnerWindow);
		}


		protected override  bool OnWindowEnum(IntPtr hWnd) 
		{
			if ( ExcludedWindows.Contains(hWnd) ) return true;

			WindowItem w = new WindowItem(hWnd,GetOwnerWindow(hWnd));
			if (Items.Contains(w))
				return true;
			if ( w.TaskVisible) {

				foreach (WindowItem wit in Items) {
					if (wit.OwnerHandle == w.OwnerHandle) return true;
				}

				base.Items.Add(w);
			}

			return true;
		}

		public List<IntPtr> ExcludedWindows {
			get { return _excWindows; }
		}

		/// <summary>
		/// returns the window which is active or topmost and visible
		/// </summary>
		public WindowItem ActiveWindow {
			get {
				IntPtr fhWnd =PWin32.GetForegroundWindow();
				IntPtr hWndDesktop = PWin32.GetDesktopWindow();
				WindowItem wi =new WindowItem(fhWnd);

				if (!wi.TaskVisible || IsHandleOrParentHandleExcluded(fhWnd) || hWndDesktop.Equals(fhWnd)  ) {
					
					CommandTS.WInfo("find the largest visible nonactive window");

					Trace.Indent();
					CommandTS.WInfo("Text		Maximised	IsTopMost		ClassName				TaskVisible		Iconic"	);
					IntPtr topWindow=PWin32.GetTopWindow(hWndDesktop);

					do {
						wi = new WindowItem(topWindow);
						topWindow = PWin32.GetWindow(wi.Handle,(uint)GW.HWNDNEXT);
						if (wi.TaskVisible && !wi.Iconic &&  !IsHandleOrParentHandleExcluded(wi.Handle ) ) {
							
							CommandTS.WInfo("'"+wi.Text + "'\t" + wi.Maximised + "\t" + wi.IsTopMost + "\t" + wi.ClassName + "\t" + wi.TaskVisible +"\t" + wi.Iconic 	);
							break;
						}
						wi = null;
					} while (topWindow != IntPtr.Zero);
					Trace.Unindent();
				
				}//if
			
				return wi;


			} //get
		}//end ActiveWindow


		private bool IsHandleOrParentHandleExcluded(IntPtr hWnd) {

			if (hWnd == IntPtr.Zero ) return false;

			return (ExcludedWindows.Contains(hWnd)|| IsHandleOrParentHandleExcluded(PWin32.GetWindow(hWnd,(uint)GW.OWNER )));

		}

	} //end class

}
